<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="用户昵称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['nickName']" placeholder="请输入用户昵称" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="服务名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['serviceName']" placeholder="请输入服务名称" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="医院名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <!-- <a-input v-decorator="['hospitalName']" placeholder="请输入医院名称" :disabled="isDisabled"/> -->
          <a-select
            show-search
            v-decorator="['hospitalId',{rules: [{ required: true,  message: '请选择就诊医院!', }]}]"
            placeholder="就诊医院"
            style="width: 100%"
           
            :defaultValue="defaultHospital"
            
            :disabled="isDisabled"
            :filter-option="filterOption"
            @popupScroll="handlePopupScroll"
            @search="handleSearch"            
            @change="handleHospitalChange"
            >
            <!-- <a-select-option v-for="a in hospitalTwoList" :key="a.id" :value="a.id">{{ a.hospitalName }}</a-select-option> -->
            <a-select-option
              v-for="(item, index) in hospitalTwoList"
              :key="index"
              :value="item.id">{{ item.hospitalName }}</a-select-option>
          
          </a-select>
        </a-form-item>
        <a-form-item label="订单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['orderSn']" placeholder="请输入订单号" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="就诊时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择就诊时间" v-decorator="['treatmentTime']"
          :disabled="isDisabled" :trigger-change="true" style="width: 100%"/>
        </a-form-item>
        <a-form-item label="就诊人名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['patientName']" placeholder="请输入就诊人名称" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['telephone']" placeholder="请输入联系电话" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="陪诊师名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['escortName']" placeholder="请输入陪诊师名称" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="应付金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number v-decorator="['payAmount']" placeholder="请输入应付金额"
                          :disabled="isDisabled" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="服务地址" :labelCol="labelCol" :wrapperCol="wrapperCol"
                     v-show="model.serviceAddress != null && model.serviceAddress != ''">
          <a-input v-decorator="['serviceAddress']" placeholder="请输入服务地址" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="收货人" :labelCol="labelCol" :wrapperCol="wrapperCol"
                     v-show="model.receiverName != null && model.receiverName != ''">
          <a-input v-decorator="['receiverName']" placeholder="请输入收货人" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="收货人手机号" :labelCol="labelCol" :wrapperCol="wrapperCol"
                     v-show="model.receiverPhone != null && model.receiverPhone != ''">
          <a-input v-decorator="['receiverPhone']" placeholder="请输入收货人手机号" :disabled="isDisabled"/>
        </a-form-item>
        <a-form-item label="收货人地址" :labelCol="labelCol" :wrapperCol="wrapperCol"
                     v-show="model.receiverProvinceName != null && model.receiverProvinceName != ''">
          <a-input v-decorator="['receiverProvinceName']" placeholder="省" :disabled="isDisabled" style="width: 30%"/>
          <a-input v-decorator="['receiverCityName']" placeholder="市" :disabled="isDisabled" style="width: 30%"/>
          <a-input v-decorator="['receiverAreaName']" placeholder="区" :disabled="isDisabled" style="width: 30%"/>
        </a-form-item>
        <a-form-item label="详细地址" :labelCol="labelCol" :wrapperCol="wrapperCol"
                     v-show="model.receiverAddress != null && model.receiverAddress != ''">
          <a-input v-decorator="['receiverAddress']" placeholder="请输入收货人手机号" :disabled="isDisabled"/>
        </a-form-item>

        <a-form-item label="服务开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择服务开始时间" v-decorator="['serviceStartTime']"
                  :disabled="isDisabled" :trigger-change="true" style="width: 100%"/>
        </a-form-item>
        <a-form-item label="服务结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择服务结束时间" v-decorator="['serviceEndTime']"
                  :disabled="isDisabled" :trigger-change="true" style="width: 100%"/>
        </a-form-item>

        <div v-show="model.status == 3">
          <a-form-item label="服用药品" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator="['takingMedicine']" placeholder="请输入服用药品" :disabled="isDisabled"/>
          </a-form-item>
          <a-form-item label="服药时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择服药时间" v-decorator="['medicationTime']"
                    :disabled="isDisabled" :trigger-change="true" style="width: 100%"/>
          </a-form-item>
          <a-form-item label="下次检查时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择下次检查时间" v-decorator="['nextInspectionTime']"
                    :disabled="isDisabled" :trigger-change="true" style="width: 100%"/>
          </a-form-item>
          <a-form-item label="服务记录图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-upload text="服务记录图片"
                      :number="6"
                      v-decorator="['serviceRecordImage']"
                      :disabled="isDisabled"
                      fileType="image"/>
          </a-form-item>
          <a-form-item label="服务记录" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-textarea v-decorator="['serviceRecord',validatorRules.serviceRecord]" placeholder="请输入服务记录"
                        :disabled="isDisabled"/>
          </a-form-item>
        </div>

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import {getAction, httpAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import {validateDuplicateValue} from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import JUpload from '@/components/jeecg/JUpload'


  export default {
    name: "MedicalServiceOrderDetailModal",
    components: {
      JDate,
      JUpload
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: "操作",
        width: 800,
        visible: false,
        isDisabled: true,
        model: {},
        hospitalList: [],
        hospitalTwoList: [],
        hospitalId:"",
        hospitalName:"",
        defaultHospital:"",
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        confirmLoading: false,
        validatorRules: {},
        url: {
          add: "/order/medicalServiceOrder/add",
          edit: "/order/medicalServiceOrder/edit",
          getHospitalList: "/hospital/medicalHospitalInfo/getList",
          
        }
      }
    },
    mounted() {
      this.initIndex();
    },
    created() {
    },
    methods: {
      handleHospitalChange(value, label) {
        
        
         this.hospitalId = value
         this.hospitalName = label.componentOptions.children[0].elm.data.trim()
        //  alert(this.hospitalName);
        
      },
      initIndex() {
        
        getAction(this.url.getHospitalList).then((res) => {
          if (res.success) {
            this.hospitalList = res.result;
            this.hospitalTwoList = res.result.slice(0, 100);  

          }
        });
      },
      add() {
        this.edit({});
      },
      edit(record) {
        this.form.resetFields();
        if (record.hospitalId) {

          this.defaultHospital = record.hospitalId;
          
          this.selectHospitalList(record.hospitalName);
          
        }
        this.model = Object.assign({}, record);
        console.info("打印日志:{}", this.model);
        this.visible = true;
        
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'receiverName', 'receiverPhone', 'receiverProvinceName', 'receiverCityName', 'receiverAreaName', 'receiverAddress', 'takingMedicine', 'medicationTime', 'serviceAddress', 'nextInspectionTime', 'serviceRecordImage', 'serviceRecord', 'nickName', 'escortName', 'patientName', 'hospitalName', 'serviceName', 'userId', 'parentId', 'serviceId', 'hospitalId', 'orderSn', 'treatmentTime', 'patientId', 'telephone', 'escortId', 'payAmount', 'payType', 'payStatus', 'payTime', 'status', 'serviceStartTime', 'serviceEndTime', 'profitRatio', 'commissionRatio', 'profitAmount', 'commissionAmount', 'allocationStatus', 'createBy', 'createTime', 'updateBy', 'updateTime', 'delFlag'))
        })
        // this.form.getFieldDecorator('hospitalId', {
        //     initialValue: '1350994191747039234'})
        this.confirmLoading = false;
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      handleOk() {
        const that = this;

        if(!this.isDisabled){
          
          // 触发表单验证
          this.form.validateFields((err, values) => {
            if (!err) {
              that.confirmLoading = true;
              let httpurl = '';
              let method = '';
              if (!that.model.id) {
                that.close();
                return;
              } else {
                httpurl += that.url.edit;
                method = 'post';
              }
              
              // let formData = Object.assign(this.model, values);

              // console.log("表单提交数据1", that.form)
              let formData = {};
              formData.orderId = that.model.id;
              formData.hospitalId = that.hospitalId;
              formData.hospitalName = that.hospitalName;
              formData.treatmentTime = that.model.treatmentTime;
              
              console.log("表单提交数据2", formData)

              httpAction(httpurl, formData, method).then((res) => {
                if (res.success) {
                  that.$message.success(res.message);
                  that.$emit('ok');
                } else {
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.close();
              })
            }

          })
        }

        that.close();
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'receiverName', 'receiverPhone', 'receiverProvinceName', 'receiverCityName', 'receiverAreaName', 'receiverAddress','takingMedicine', 'medicationTime', 'serviceAddress', 'nextInspectionTime', 'serviceRecordImage', 'serviceRecord', 'userId', 'parentId', 'serviceId', 'hospitalId', 'orderSn', 'treatmentTime', 'patientId', 'telephone', 'escortId', 'payAmount', 'payType', 'payStatus', 'payTime', 'status', 'serviceStartTime', 'serviceEndTime', 'profitRatio', 'commissionRatio', 'profitAmount', 'commissionAmount', 'allocationStatus', 'createBy', 'createTime', 'updateBy', 'updateTime', 'delFlag'))
      },
      
      selectHospitalList(value) {
        let param = {hospitalName: value};
        
        //通过接口获取数据
        getAction(this.url.getHospitalList, param).then((res) => {
          if (res.success) {
            let newList = res.result;
            if (newList.length > 100) {
              this.hospitalTwoList = res.result;
            } else {
              this.hospitalTwoList = res.result;
              this.hospitalList.forEach(item => {
                if (item.hospitalName.indexOf(value) < 0 && this.hospitalTwoList.length < 100) {

                  this.hospitalTwoList.push(item);
                }
              });
            }
            this.confirmLoading = false;
            console.info("result:{}", res.result)
          }
        });
      },
      handleSearch(value) {
        console.info("打印value：{}", value);
        this.valueData = value;
        let newList = [];
        if (value) {
          //有值搜索时进行for循环
          this.hospitalList.forEach(item => {
            if (item.hospitalName.indexOf(value) >= 0) {
              newList.push(item);
            }
          });
          this.hospitalTwoList = newList;
        } else {
          //没有值时进行第一页截取
          this.hospitalTwoList = [];
          this.scrollPage = 1;
          this.hospitalTwoList = this.hospitalList.slice(0, 100);
        }
      },
      handlePopupScroll(e) {
        //下拉框下滑事件
        const {target} = e;
        const scrollHeight = target.scrollHeight - target.scrollTop;
        const clientHeight = target.clientHeight;
        // 下拉框不下拉的时候
        if (scrollHeight === 0 && clientHeight === 0) {
          this.scrollPage = 1;
          console.log(this.scrollPage);
        } else {
          // 当下拉框滚动条到达底部的时候
          if (scrollHeight < clientHeight + 5) {
            this.scrollPage = this.scrollPage + 1;
            const scrollPage = this.scrollPage;// 获取当前页
            const treePageSize = this.treePageSize * (scrollPage || 1);// 新增数据量
            const newData = [];// 存储新增数据
            let max = ''; // max 为能展示的数据的最大条数
            if (this.hospitalList.length > treePageSize) {
              // 如果总数据的条数大于需要展示的数据
              max = treePageSize;
            } else {
              // 否则
              max = this.hospitalList.length;
            }
            //判断是否有搜索，带了搜索走搜索的方法如果下拉不进行操作
            console.info("valueData:{}", this.valueData)
            if (!this.valueData) {
              this.hospitalList.forEach((item, index) => {
                if (index < max) { // 当data数组的下标小于max时
                  newData.push(item);
                }
              })
              //将新增的数据赋值到要显示的数组中
              this.hospitalTwoList = newData;
            }
          }
        }
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      }

    }
  }
</script>